package com.share.finance.risk.pre.service.impl;

import com.alibaba.fastjson.JSON;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import com.share.common.enums.EventTypeEnum;
import com.share.config.kafka.KafkaSender;
import com.share.config.kafka.SendVo;
import com.share.finance.risk.common.model.sys.PreRequest;
import com.share.finance.risk.pre.service.CreditLoanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CreditLoanServiceImpl implements CreditLoanService {
    @Autowired
    private KafkaSender kafkaSender;

    @Override
    public Result applyCreditLoan(PreRequest req) {
        Result result = null;
        String jsonReq = JSON.toJSONString(req);
        log.info("applyCreditLoan接收到参数req={}", jsonReq);
        try {
            //1.参数校验---内部会抛异常
            checkParam(req);

            //2.执行业务
            EventTypeEnum eventType = EventTypeEnum.getEnumByCode(req.getEventType());
            if (eventType == null) {
                throw new RuntimeException("缺少配置eventType=" + req.getEventType());
            }
            log.info("发送到kafka,topic={},data={}", eventType.getTopic(), jsonReq);
            SendVo send = kafkaSender.send(eventType.getTopic(), jsonReq);
            if (send.isSuccess()) {
                result = Result.success(send);
            } else {
                result = Result.failure(send);
            }
        } catch (Exception e) {
            log.info("发送消息至kafka失败,req={}", jsonReq, e);
            result = Result.failure(ErrMsgEnum.FAILURE_SYS_ERROR);
            result.setData(e);
        }
        return result;
    }

    private void checkParam(PreRequest req) {
        if (EventTypeEnum.getEnumByCode(req.getEventType()) == null) {
            throw new RuntimeException("eventType传输错误");
        }
    }

}
